<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/5/11
 * Time: 下午3:25
 */

namespace App\Lib;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Illuminate\Support\Str;

class Shumei
{
    private $agoraAppId;
    private $accessKey;
    private $shumeiBaseUrl;
    private $appId;
    private $shumeiAntiCheatingUrl;
    const ANTI_FRAUD_BASE_URL = 'http://api-tw-bj.fengkongcloud.com/v3/event';

    public function __construct()
    {
        $configAgora = config('agora');
        $this->agoraAppId = $configAgora['appId'];
        $config = config('sumei');
        $this->accessKey = $config['accessKey'];
        $this->appId = $config['appId'];
        $this->shumeiBaseUrl = 'http://api-audiostream-bj.fengkongcloud.com';
        //渠道流量反作弊URL
        $this->shumeiAntiCheatingUrl = 'http://api-skynet-bj.fengkongcloud.com';

    }

    /**
     * 添加任务到
     * @param $roomId 房间Id
     * @param $callBackUrl 问题CallBack
     * @param $isMixingEnabled 是否禁用分流
     * @return string 返回requestId 可做任务Id使用
     */
    public function addTask($roomId, $agoraToken, $agoraUid, $callBackUrl, $isMixingEnabled)
    {
        $voiceId = makeUuid(32);
        $requestData = [
            'accessKey' => $this->accessKey,
            'type' => 'POLITICAL_PORN_MOAN_AD',
            'btid' => $voiceId,
            'callback' => $callBackUrl
        ];
        $requestData['data'] = [
            'streamType' => 'AGORA',
            'audioName' => '房间' . $roomId,
            'room' => strval($roomId),
            'returnAllText' => false,
            'returnPreText' => true,
            'returnPreAudio' => true,
            'tokenId' => '0',
            'channel' => 'VOICE_ROOM',
            'ip' => '127.0.0.1',
        ];
        $requestData['data']['agoraParam'] = [
            'appId' => $this->agoraAppId,
            'channel' => strval($roomId),
            'channelKey' => $agoraToken,
            'uid' => $agoraUid,
            'isMixingEnabled' => $isMixingEnabled,
        ];
        write_log('sumei', 'addtask', $requestData);
        $result = curl_request($this->shumeiBaseUrl . '/v2/saas/anti_fraud/audiostream', $requestData, 'json');
        write_log('sumei', 'addtask_result:房间room_id:'.$roomId, $result);
        $result = json_decode($result, true);
        if (!isset($result['code'])) {
            return null;
        }
        if ($result['code'] != 1100) {
            return null;
        }
        return $result['requestId'];
    }


    /**
     * 查询当前检测的任务
     */
    public function queryTask()
    {
        $requestData = [
            'accessKey' => $this->accessKey,
        ];
        write_log('sumei', 'querytask', $requestData);
        $result = curl_request($this->shumeiBaseUrl . '/v2/saas/anti_fraud/query_audiostream', $requestData, 'json');
        write_log('sumei', 'querytask_result', $result);
        $result = json_decode($result, true);
        if (!isset($result['code'])) {
            return null;
        }
        if ($result['code'] != 1100) {
            return null;
        }
        if (!isset($result['detail'])){
            return [];
        }
        return $result['detail'];
    }


    /**
     * 删除检测的任务
     * @param $requestId
     * @return string requestId
     */
    public function delTask($requestId)
    {
        $requestData = [
            'accessKey' => $this->accessKey,
            'requestId' => $requestId
        ];

        write_log('sumei', 'deltask', $requestData);
        $result = curl_request($this->shumeiBaseUrl . '/v2/saas/anti_fraud/finish_audiostream', $requestData, 'json');
        write_log('sumei', 'deltask_result', $result);
        $result = json_decode($result, true);
        if (!isset($result['code'])) {
            return null;
        }
        if ($result['code'] != 1100) {
            return null;
        }
        return $result['requestId'];
    }


    /**
     * 检测图片
     * @param $userId
     * @param $imgUrl
     * @return int 1.放行 2.人工审核 3.拒绝 4.异常
     */
    public function filterImage($userId, $imgUrl)
    {
        $postData = [];
        $postData['accessKey'] = $this->accessKey;
        //$postData['type'] = 'DEFAULT';
        $postData['appId'] = 'default';
        //$postData['callback'] = $cbUrl;

        $dataParams = [];
        $dataParams['tokenId'] = strval($userId); // 设置tokenId, 由客户提供
        $dataParams['img'] = $imgUrl; // 设置图片参数，这里也可以提供图片的 http 后者 https 链接

        $postData['data'] = $dataParams;

        write_log('sumei', 'filterImage', $postData);
        $result = curl_request('http://api-img-bj.fengkongcloud.com/v2/saas/anti_fraud/img', $postData, 'json');
        write_log('sumei', 'filterImage', $result);

        $resJson = json_decode($result, true);

        /**
         * 接口会返回code， code=1100 时说明请求成功，根据不同的 riskLevel 风险级别进行业务处理
         * 当 code!=1100 时，如果是 1902 错误，需要检查参数配置
         * 其余情况需要根据错误码进行重试或者其它异常处理
         */
        if ($resJson["code"] == 1100) {
            if ($resJson["riskLevel"] == "PASS") {
                // 放行
                return 1;
            } else if ($resJson["riskLevel"] == "REVIEW") {
                // 人工审核，如果没有审核，就放行
                return 2;
            } else if ($resJson["riskLevel"] == "REJECT") {
                // 拒绝
                return 3;
            } else {
                // 异常
                return 4;
            }
        } else {
            // 接口请求失败，需要参照返回码进行不同的处理
        }
    }

    /**
     * 数美渠道流量反作弊检测
     * @param $data           //user-Agent解析出的数据
     * @param $deviceId       //数美设备指纹标识
     * @param $advertisingId  //广告计费的设备ID
     * @return mixed|null
     */
    public function antiCheating($data, $deviceId, $advertisingId)
    {
        $requestData = [
            'accessKey' => $this->accessKey,
            'appId' => $this->appId,
            'eventId' => 'activation',
            'isTokenSeperate' => 0, //是否区分账号体系 同公司不同app接入，需要区分账号体系，0，不区分，1，区分
        ];
        $requestData['data'] = [
            'ip' => client_ip(),  //客户端公网ipv4地址
            'timestamp' => time() * 1000,  //毫秒时间戳
            'advertisingId' => $advertisingId ?? "",  //一般是安卓的IMEI或苹果设备的IDFA。可以传入哈希值
            'apputm' => $data['channel_id'],  //本次注册的渠道标识
            'os' => $data['os_name'],  //可选值： android、ios、weapp、web
            'appVersion' => $data['version_no'],  //应用版本号传入当前应用或服务正在使用的版本号，格式为3个点4段数字，每段数字最多4位，例如3.2.1.1234。不足4段的请补0，例如2.1.5传入2.1.5.0。多于4段的取前4段，例如2.1.5.1.1传入2.1.5.1.
            'deviceId' => $deviceId  //数美设备指纹标识
        ];
        write_log('sumei', 'requestAntiCheating', $requestData);
        $result = curl_request($this->shumeiAntiCheatingUrl . '/v3/event', $requestData, 'json');
        write_log('sumei', 'requestAntiCheating_result', $result);
        $result = json_decode($result, true);
        if (!isset($result['code'])) {
            return null;
        }
        if ($result['code'] != 1100) {
            return null;
        }
        return $result;
    }

    /**
     * 数美反欺诈
     * 
     * @param string $eventId 事件 ID，用于标识事件类型。 示例: login、register
     * @param array $data 本次请求相关信息
     * @return array
     */
    public function antiFraudCheck(string $eventId = 'login', array $data = []) {
        $data = [
            'accessKey' => $this->accessKey,
            'appId' => $this->appId,
            'eventId' => $eventId,
            'data' => $data
        ];

        return json_decode(curl_request(self::ANTI_FRAUD_BASE_URL, $data, 'json'), true);
    }
}
